import re

from django import forms
from django.contrib.auth.hashers import make_password, check_password
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError

from .models import UserProfile


class RegisterForm(forms.Form):
    """注册"""
    mobile = forms.CharField(
        required=True,
        error_messages={
            "required": "用户名不能为空",
        }
    )

    email = forms.EmailField(
        required=True,
        error_messages={
            "required": "密码不能为空",
        }
    )

    image_code = forms.CharField(
        required=True,
        error_messages={
            "required": "验证码不能为空",
        }
    )

    password = forms.CharField(
        required=True,
        min_length=6,
        max_length=20,
        error_messages={
            "required": "密码不能为空",
            "min_length": "密码长度最少6位数",
            "max_length": "密码长度最长20位数",
        }
    )

    confirm_password = forms.CharField(
        required=True,
        min_length=6,
        max_length=20,
        error_messages={
            "required": "密码不能为空",
            "min_length": "密码长度最少6位数",
            "max_length": "密码长度最长20位数",
        }
    )

    def clean(self):
        """这里面的错误会在 non_field_errors 中显示"""
        cleaned_data = self.cleaned_data
        mobile = cleaned_data.get('mobile')
        email = cleaned_data.get('email')
        password = cleaned_data.get('password')
        confirm_password = cleaned_data.get('confirm_password')

        if not all([mobile, email, password, confirm_password]):
            raise ValidationError('输入框不能为空')

        REGEX_MOBILE = "^1[3578]\d{9}$|^147\d{8}$|^176\d{8}$"
        if not re.match(REGEX_MOBILE, mobile):
            raise ValidationError("手机号码格式不合法")

        if UserProfile.objects.filter(mobile=mobile).count():
            raise ValidationError('用户名：{}已被注册'.format(mobile))

        if UserProfile.objects.filter(email=email).count():
            raise ValidationError('邮箱：{}已被注册'.format(email))

        if password != confirm_password:
            raise ValidationError("两次密码输入不一致")

        # regex_password = '^(?:(?=.*[A-Za-z])(?=.*[a-z])(?=.*[0-9])).{6,20}$'
        # for i in [password, confirm_password]:
        #     if not re.match(regex_password, i):
        #         raise ValidationError('密码必须是字母数字组合，长度6-20位')


class LoginForm(forms.Form):
    """登陆"""
    mobile = forms.CharField(
        required=True,
        error_messages={
            "required": "用户名不能为空",
        }
    )

    password = forms.CharField(
        required=True,
        min_length=6,
        max_length=20,
        error_messages={
            "required": "密码不能为空",
            "min_length": "密码长度最少6位数",
            "max_length": "密码长度最长20位数",
        }
    )

    image_code = forms.CharField(
        required=True,
        error_messages={
            "required": "验证码不能为空",
        }
    )

    def clean(self):
        """这里面的错误会在 non_field_errors 中显示"""
        cleaned_data = self.cleaned_data
        mobile = cleaned_data.get('mobile')
        image_code = cleaned_data.get('image_code')
        password = cleaned_data.get('password')

        if not all([mobile, image_code, password]):
            raise ValidationError('输入框不能为空')

        REGEX_MOBILE = "^1[3578]\d{9}$|^147\d{8}$|^176\d{8}$"
        if not re.match(REGEX_MOBILE, mobile):
            raise ValidationError("手机号码格式不合法")

        user = UserProfile.objects.filter(mobile=mobile)
        if user.count() == 0:
            raise ValidationError('用户名不存在')

        origin_password = user[0].password

        # if check_password(password, origin_password):
        #     raise ValidationError("密码错误，请重新输入")


class ResetForm(forms.Form):
    """重置密码"""
    email = forms.EmailField(
        required=True,
        error_messages={
            "required": "邮箱不能为空",
        }
    )

    code = forms.CharField(
        required=True,
        error_messages={
            "required": "验证码不能为空",
        }
    )

    password = forms.CharField(
        required=True,
        min_length=6,
        max_length=20,
        error_messages={
            "required": "密码不能为空",
            "min_length": "密码长度最少6位数",
            "max_length": "密码长度最长20位数",
        }
    )

    confirm_password = forms.CharField(
        required=True,
        min_length=6,
        max_length=20,
        error_messages={
            "required": "密码不能为空",
            "min_length": "密码长度最少6位数",
            "max_length": "密码长度最长20位数",
        }
    )

    def clean(self):
        """这里面的错误会在 non_field_errors 中显示"""
        cleaned_data = self.cleaned_data
        password = cleaned_data.get('password')
        confirm_password = cleaned_data.get('confirm_password')

        regex_password = '^(?:(?=.*[A-Za-z])(?=.*[a-z])(?=.*[0-9])).{6,20}$'
        for i in [password, confirm_password]:
            if not re.match(regex_password, i):
                raise ValidationError('密码必须是字母数字组合，长度6-20位')

        if password != confirm_password:
            raise ValidationError("两次密码输入不一致")


class ChangePasswordForm(forms.Form):
    """修改密码"""

    origin_password = forms.CharField(
        required=True,
        min_length=6,
        max_length=20,
        error_messages={
            "required": "密码不能为空",
            "min_length": "密码长度最少6位数",
            "max_length": "密码长度最长20位数",
        }
    )

    password = forms.CharField(
        required=True,
        min_length=6,
        max_length=20,
        error_messages={
            "required": "密码不能为空",
            "min_length": "密码长度最少6位数",
            "max_length": "密码长度最长20位数",
        }
    )

    confirm_password = forms.CharField(
        required=True,
        min_length=6,
        max_length=20,
        error_messages={
            "required": "密码不能为空",
            "min_length": "密码长度最少6位数",
            "max_length": "密码长度最长20位数",
        }
    )

    def clean(self):
        cleaned_data = self.cleaned_data
        password = cleaned_data.get('password')
        confirm_password = cleaned_data.get('confirm_password')

        if not all([password, confirm_password]):
            raise ValidationError('输入框不能为空')

        regex_password = '^(?:(?=.*[A-Za-z])(?=.*[a-z])(?=.*[0-9])).{6,20}$'
        for i in [password, confirm_password]:
            if not re.match(regex_password, i):
                raise ValidationError('密码必须是字母数字组合，长度6-20位')


class ChangeEmailForm(forms.Form):
    """修改邮箱"""

    new_email = forms.EmailField(
        required=True,
        error_messages={
            "required": "邮箱不能为空",
        }
    )
